#!/usr/bin/env python3
"""
FEC配置模块 - 包含FEC配置相关的函数
"""

import asyncio
import random
from aiortc_custom.rtcrtpparameters import RTCRtpDecodingParameters
from aiortc_custom.logger_config import log_info, log_debug, log_success, log_error, log_fec, log_fec_success, log_fec_error, log_fec_config


async def configure_receivers_with_fec(pc, fec_controller):
    """配置接收器FEC参数"""
    try:
        log_fec_config("开始配置接收器FEC参数...")
        receivers = pc.getReceivers()
        log_fec("找到 {len} 个接收器", len=len(receivers))
        
        for receiver in receivers:
            log_debug("配置接收器: {receiver}", receiver=receiver)
            
            # 检查接收器类型（通过track属性判断）
            is_video_receiver = False
            if hasattr(receiver, '_track') and receiver._track:
                if receiver._track.kind == 'video':
                    is_video_receiver = True
            elif hasattr(receiver, '__kind') and receiver.__kind == 'video':
                is_video_receiver = True
            
            if is_video_receiver:
                log_fec_success("检测到视频接收器，配置FEC")
                # 注意：在aiortc_custom中，接收器的FEC配置通常在创建时设置
                # 这里我们只是记录FEC配置信息
                fec_config = fec_controller.get_fec_config()
                if fec_config:
                    log_fec_success("接收器FEC配置: {fec_type}, k={k}, n={n}", 
                                  fec_type=fec_config.fec_type, k=fec_config.k, n=fec_config.n)
                else:
                    log_fec("接收器FEC配置: 未启用")
            else:
                log_fec("跳过非视频接收器")
                
    except Exception as e:
        log_fec_error("配置接收器FEC参数时出错: {e}", e=e)
        import traceback
        traceback.print_exc()


async def configure_senders_with_fec(pc, fec_controller):
    """配置发送器FEC参数"""
    try:
        log_fec_config("开始配置发送器FEC参数...")
        senders = pc.getSenders()
        log_fec("找到 {len} 个发送器", len=len(senders))
        
        # 如果发送器没有初始化完毕，等待并重试
        if len(senders) == 0:
            log_fec("发送器尚未初始化，等待100ms后重试...")
            await asyncio.sleep(0.1)
            senders = pc.getSenders()
            log_fec("重试后找到 {len} 个发送器", len=len(senders))
        
        for i, sender in enumerate(senders):
            log_debug("配置发送器 {i}: {sender}", i=i, sender=sender)
            
            # 添加详细的发送器属性调试信息
            log_fec("发送器 {i} 属性检查:", i=i)
            log_fec("  - hasattr(sender, '_track'): {has_track}", has_track=hasattr(sender, '_track'))
            if hasattr(sender, '_track'):
                log_fec("  - sender._track: {track}", track=sender._track)
                if sender._track:
                    log_fec("  - sender._track.kind: {kind}", kind=sender._track.kind)
            log_fec("  - hasattr(sender, '__kind'): {has_kind}", has_kind=hasattr(sender, '__kind'))
            if hasattr(sender, '__kind'):
                log_fec("  - sender.__kind: {kind}", kind=sender.__kind)
            
            # 检查发送器类型（使用多种方法检测）
            is_video_sender = False
            is_audio_sender = False
            
            # 方法1：通过发送器索引（第一个发送器通常是视频，第二个是音频）
            if i == 0:
                log_fec("发送器 {i} 是第一个发送器，假设为视频发送器", i=i)
                is_video_sender = True
            elif i == 1:
                log_fec("发送器 {i} 是第二个发送器，假设为音频发送器", i=i)
                is_audio_sender = True
            
            # 方法2：通过编解码器类型判断
            if not is_video_sender and not is_audio_sender:
                try:
                    parameters = sender.getParameters()
                    log_fec("发送器 {i} 参数: {parameters}", i=i, parameters=parameters)
                    for codec in parameters.codecs:
                        log_fec("编解码器: {mimeType}", mimeType=codec.mimeType)
                        if codec.mimeType.startswith('video/'):
                            is_video_sender = True
                            break
                        elif codec.mimeType.startswith('audio/'):
                            is_audio_sender = True
                            break
                except Exception as e:
                    log_fec("获取发送器 {i} 参数失败: {e}", i=i, e=e)
            
            # 方法3：通过track属性判断
            if not is_video_sender and not is_audio_sender:
                if hasattr(sender, '_track') and sender._track:
                    if sender._track.kind == 'video':
                        is_video_sender = True
                    elif sender._track.kind == 'audio':
                        is_audio_sender = True
                elif hasattr(sender, '__kind'):
                    if sender.__kind == 'video':
                        is_video_sender = True
                    elif sender.__kind == 'audio':
                        is_audio_sender = True
            
            # 为视频和音频发送器都配置FEC
            if is_video_sender or is_audio_sender:
                sender_type = "视频" if is_video_sender else "音频"
                log_fec_success("检测到{sender_type}发送器，配置FEC", sender_type=sender_type)
                
                # 设置FEC配置
                fec_config = fec_controller.get_fec_config()
                if fec_config:
                    # 获取发送器参数
                    parameters = sender.getParameters()
                    parameters.fec_config = fec_config
                    parameters.fec_ssrc = random.randint(1000000, 9999999)  # 随机生成FEC SSRC
                    
                    # 应用参数
                    await sender.setParameters(parameters)
                    log_fec_success("发送器FEC配置完成: {fec_type}, k={k}, n={n}, FEC SSRC={fec_ssrc}", 
                                  fec_type=fec_config.fec_type, k=fec_config.k, n=fec_config.n, fec_ssrc=parameters.fec_ssrc)
                else:
                    log_fec("发送器FEC配置: 未启用")
            else:
                log_fec("跳过未知类型发送器")
                
    except Exception as e:
        log_fec_error("配置发送器FEC参数时出错: {e}", e=e)
        import traceback
        traceback.print_exc()


def get_fec_type_info():
    """获取FEC类型信息"""
    return {
        "repetition": {
            "name": "repetition (重复编码) - 默认",
            "description": "通过重复发送数据包来提供冗余",
            "default_k": 2,
            "default_n": 4
        },
        "xor": {
            "name": "xor (异或编码)",
            "description": "使用异或运算生成冗余包",
            "default_k": 3,
            "default_n": 6
        },
        "reed_solomon": {
            "name": "reed_solomon (里德-所罗门编码)",
            "description": "使用里德-所罗门算法提供强大的错误纠正能力",
            "default_k": 4,
            "default_n": 8
        }
    }


def display_fec_selection_menu():
    """显示FEC选择菜单"""
    fec_types = get_fec_type_info()
    
    log_info("\n选择FEC配置:")
    for i, (fec_type, info) in enumerate(fec_types.items(), 1):
        log_info("{i}. {name}: {description}", 
                i=i, name=info["name"], description=info["description"])
    log_info("4. 禁用FEC")


def parse_fec_choice(choice):
    """解析FEC选择"""
    fec_types = get_fec_type_info()
    
    if choice == "1" or not choice:
        return "repetition", 2, 4
    elif choice == "2":
        return "xor", 3, 6
    elif choice == "3":
        return "reed_solomon", 4, 8
    elif choice == "4":
        return None, 0, 0
    else:
        return "repetition", 2, 4  # 默认值